package com.bhs.sansonglogistics.ui.message;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.base.GlideEngine;
import com.bhs.sansonglogistics.bean.CircleFriendsBean;
import com.bhs.sansonglogistics.bean.CircleFriendsData;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.bean.event.CircleRefresh;
import com.bhs.sansonglogistics.bean.event.ClearMessage;
import com.bhs.sansonglogistics.bean.event.MessageCenterRefresh;
import com.bhs.sansonglogistics.bean.event.NewMessage;
import com.bhs.sansonglogistics.bean.event.ViewPageStatus;
import com.bhs.sansonglogistics.dialog.BottomSelectDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.CircleFriendsAdapter;
import com.bhs.sansonglogistics.ui.adapter.PictureSelectAdapter;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 圈子
 */
public class CircleFriendsFragment extends BaseFragment implements NetCallBack, View.OnClickListener {

    private ImageView mBgCover;
    private TextView mTvCompanyName;
    private ShapeableImageView mIvFace;
    private ShapeableImageView mIvMessageFace;
    private TextView mTvNewMessage;
    private RecyclerView mRvList;
    private ImageView mIvIssue;
    private CircleFriendsAdapter mAdapter;
    private SwipeRefreshLayout mRefreshLayout;
    private int page = 1;
    private String uid;
    private String name;
    private String face;
    private String cover;
    private int logistics_id;
    private NestedScrollView mNestedScrollView;
    private ViewGroup mViewGroup;
    private int xDelta;
    private int yDelta;
    private String myUnid;
    private CircleReuse circleReuse;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private int mPosition;
    private int mIvIssueWidth;
    private int mIvIssueHeight;
    private int mViewGroupBottom;
    private int screenWidth;
    private ProgressBar mProgressBar;
    private LinearLayout mLlNewMessage;
    private int type = 0;

    public static CircleFriendsFragment newInstance(Bundle bundle) {
        CircleFriendsFragment fragment = new CircleFriendsFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_circle_friends;
    }

    @Override
    public void initView(View root) {
        myUnid = SharedPreferencesUtils.getString(getContext(), "uid");
        mBgCover = root.findViewById(R.id.bg_cover);
        mTvCompanyName = root.findViewById(R.id.tv_company_name);
        mIvFace = root.findViewById(R.id.iv_face);
        mIvMessageFace = root.findViewById(R.id.iv_message_face);
        mTvNewMessage = root.findViewById(R.id.tv_new_message);
        mRvList = root.findViewById(R.id.rv_list);
        mIvIssue = root.findViewById(R.id.iv_issue);
        mIvIssue.setOnClickListener(this);
        mIvFace.setOnClickListener(this);
        mRefreshLayout = root.findViewById(R.id.refreshLayout);
        mNestedScrollView = root.findViewById(R.id.NestedScrollView);
        mViewGroup = root.findViewById(R.id.root);
        mProgressBar = root.findViewById(R.id.ProgressBar);
        mLlNewMessage = root.findViewById(R.id.ll_new_message);
        mLlNewMessage.setOnClickListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void prestrain() {
        super.prestrain();
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null) {
                    if (result.getResultCode() == 2) {
                        mAdapter.remove(mPosition);
                    } else if (result.getResultCode() == 1) {
                        CircleFriendsBean circleFriendsBean = (CircleFriendsBean) result.getData().getSerializableExtra("data");
                        if (circleFriendsBean.getJudgeList().size() > 10) {
                            circleFriendsBean.setJudgeList(circleFriendsBean.getJudgeList().subList(0, 9));
                        }
                        mAdapter.getData().set(mPosition, circleFriendsBean);
                        mAdapter.notifyItemChanged(mPosition, 0);
                    }
                }
            }
        });
    }

    @Override
    public void initData() {
        if (getArguments() != null) {
            name = getArguments().getString("name");
            face = getArguments().getString("face");
            uid = getArguments().getString("uid");
            type = getArguments().getInt("type", 0);
            mTvCompanyName.setText(name);
            Glide.with(getContext()).load(face).into(mIvFace);
            logistics_id = SharedPreferencesUtils.getInt(getContext(), "logistics_id", 0);
            cover = getArguments().getString("BgCover");
        }
        if (!TextUtils.isEmpty(cover)) {
            Glide.with(getContext()).load(cover).into(mBgCover);
        }
        if (type == 1) {
            mBgCover.setOnClickListener(this);
        }
        mAdapter = new CircleFriendsAdapter((BaseActivity) getActivity());
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData();
            }
        });
        mAdapter.setEmptyView(LayoutInflater.from(getContext()).inflate(R.layout.layout_empty, null));
        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    page++;
                    loadData();
                }
            }
        });

        loadData();

        mIvIssue.post(new Runnable() {
            @Override
            public void run() {

                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.leftMargin = (int) mIvIssue.getX();
                layoutParams.topMargin = (int) mIvIssue.getY();

                mIvIssue.setLayoutParams(layoutParams);
                mIvIssueWidth = mIvIssue.getWidth();
                mIvIssueHeight = mIvIssue.getHeight();
                mViewGroupBottom = mViewGroup.getBottom();
                screenWidth = MyUtils.getScreenWidth(getContext());
            }
        });


        mIvIssue.setOnTouchListener(movingEventListener);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mPosition = position;
                intentActivityResultLauncher.launch(new Intent(getActivity(), CircleDetailActivity.class)
                        .putExtra("data", mAdapter.getData().get(position)));
            }
        });

        circleReuse = new CircleReuse((BaseActivity) getActivity(), myUnid);
        circleReuse.clickEvent(mAdapter);

    }


    private View.OnTouchListener movingEventListener = new View.OnTouchListener() {
        int downX, downY;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            final int x = (int) event.getRawX();
            final int y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    EventBus.getDefault().post(new ViewPageStatus(false));
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view
                            .getLayoutParams();
                    xDelta = x - params.leftMargin;
                    yDelta = y - params.topMargin;
                    downX = (int) event.getRawX();
                    downY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:

                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                            .getLayoutParams();
                    int xDistance = x - xDelta;
                    int yDistance = y - yDelta;
                    if (xDistance > 0 && yDistance > 0 && (xDistance + mIvIssueWidth < screenWidth)
                            && (yDistance + mIvIssueHeight < mViewGroupBottom)) {
                        layoutParams.leftMargin = xDistance;
                        layoutParams.topMargin = yDistance;
                        view.setLayoutParams(layoutParams);
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    EventBus.getDefault().post(new ViewPageStatus(true));
                    //检测移动的距离，如果很微小可以认为是点击事件
                    if (Math.abs(event.getRawX() - downX) < 10 && Math.abs(event.getRawY() - downY) < 10) {
                        try {
                            Field field = View.class.getDeclaredField("mListenerInfo");
                            field.setAccessible(true);
                            Object object = field.get(view);
                            field = object.getClass().getDeclaredField("mOnClickListener");
                            field.setAccessible(true);
                            object = field.get(object);
                            if (object != null && object instanceof View.OnClickListener) {
                                ((View.OnClickListener) object).onClick(view);
                            }
                        } catch (Exception e) {
                        }
                    }
                    break;
            }
            mViewGroup.invalidate();
            return true;
        }
    };


    Map<String, String> map = new ArrayMap<>();

    private void loadData() {
        map.put("page", String.valueOf(page));
        map.put("limit", "10");
        if (!TextUtils.isEmpty(uid)) {
            map.put("keyword_unid", uid);
        }
        networkRequest(netApi.circleList(map), this, 666);
        if (page == 1) {
            networkRequest(netApi.set_circle_red_time(), null);
        }
    }

    private String circle_pic;

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 666) {
            mProgressBar.setVisibility(View.GONE);
            mRefreshLayout.setRefreshing(false);
            CircleFriendsData dataBean = new Gson().fromJson(json, CircleFriendsData.class);
            if (page == 1) {
                mAdapter.setNewData(dataBean.getData().getList());
            } else {
                mAdapter.loadMoreComplete();
                mAdapter.addData(dataBean.getData().getList());
            }
            if (mAdapter.getData().size() >= dataBean.getData().getTotal_count()) {
                mAdapter.loadMoreEnd();
            }
        } else if (requestCode == 47) {
            ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
            if (dataBean.isStatus()) {
                circle_pic = dataBean.getData().getSrc();
                networkRequest(netApi.addCirclePic(dataBean.getData().getSrc()), CircleFriendsFragment.this, 9528);
                Glide.with(getContext()).load(dataBean.getData().getSrc()).into(mBgCover);
            } else {
                ((BaseActivity) getActivity()).loadingPopupDismiss();
                ToastUtil.show("网络异常");
            }
        } else if (requestCode == 9528) {
            ((BaseActivity) getActivity()).loadingPopupDismiss();
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.getCode().equals("1")) {
                SharedPreferencesUtils.saveString(getContext(), "circle_pic", circle_pic);
                ToastUtil.show("更换成功");
            } else {
                ToastUtil.show("网络异常");
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        ((BaseActivity) getActivity()).loadingPopupDismiss();
        mRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
        mProgressBar.setVisibility(View.GONE);
    }

    private int SelectType;//1=发作品 2=换圈子

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_issue) {
            //mNestedScrollView.fullScroll(ScrollView.FOCUS_UP);
            //startActivity(new Intent(getContext(), IssueCircleFriendsActivity.class));
            SelectType = SelectMimeType.TYPE_ALL;
            bottomSelect();
        } else if (view.getId() == R.id.iv_face) {
            startActivity(new Intent(getContext(), CirclePersonageActivity.class)
                    .putExtra("uid", myUnid)
                    .putExtra("logistics_id", logistics_id));
        } else if (view.getId() == R.id.ll_new_message) {
            messageQuantity = 0;
            mLlNewMessage.setVisibility(View.GONE);
            startActivity(new Intent(getContext(), CircleFriendsMessageActivity.class));
            EventBus.getDefault().post(new ClearMessage());
        } else if (view.getId() == R.id.bg_cover) {
            SelectType = SelectMimeType.TYPE_IMAGE;
            bottomSelect();
        }
    }

    private BasePopupView basePopupView;
    private BottomSelectDialog bottomSelectDialog;

    private void bottomSelect() {
        if (basePopupView == null) {
            bottomSelectDialog = new BottomSelectDialog(getContext());
            bottomSelectDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.tv_take_picture) {
                        photograph();
                    } else if (v.getId() == R.id.tv_photo_album) {
                        photoAlbum();
                    }
                    basePopupView.dismiss();
                }
            });
            basePopupView = new XPopup.Builder(getContext())
                    .asCustom(bottomSelectDialog)
                    .show();

        } else {
            basePopupView.show();
        }
    }

    private void photoAlbum() {
        PictureSelector.create(getContext())
                .openGallery(SelectType)
                .setMaxSelectNum(9)
                .setMaxVideoSelectNum(1)
                .setRecordVideoMaxSecond(30)
                .setFilterVideoMaxSecond(31)
                .setVideoThumbnailListener(new PictureSelectAdapter.MeOnVideoThumbnailEventListener())
                .isWithSelectVideoImage(false)
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        dispose(result);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void dispose(ArrayList<LocalMedia> result) {
        if (SelectType == SelectMimeType.TYPE_ALL) {
            startActivity(new Intent(getContext(), IssueCircleFriendsActivity.class)
                    .putExtra("data", result));
        } else {
            MyUtils.imageUpload((BaseActivity) getActivity(), result, this, 47);
        }
    }

    private void photograph() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.TYPE_ALL)
                .setRecordVideoMaxSecond(30)
                .setVideoThumbnailListener(new PictureSelectAdapter.MeOnVideoThumbnailEventListener())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        dispose(result);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Subscribe
    public void onEvent(CircleRefresh event) {
        page = 1;
        loadData();
    }

    @Subscribe
    public void onEvent(ClearMessage event) {
        mLlNewMessage.setVisibility(View.GONE);
    }


    int messageQuantity;

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(NewMessage event) {
        if (type == 1) {
            if (!event.getType().equals("666")) {
                mLlNewMessage.setVisibility(View.VISIBLE);
                Glide.with(getContext()).load(event.getHeadImg()).into(mIvMessageFace);
                messageQuantity++;
                mTvNewMessage.setText(String.format("%s条新消息", messageQuantity));
                page = 1;
            }
            loadData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}